package com.gln.bloger.service.impl;

import org.hibernate.Hibernate;

import com.gln.bloger.dao.UserDao;
import com.gln.bloger.exception.AlreadyExistException;
import com.gln.bloger.exception.BlogerException;
import com.gln.bloger.pojos.User;
import com.gln.bloger.service.UserService;
import com.gln.bloger.util.StringUtil;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
    
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public User getUser(String mail) throws BlogerException {
		User user =  getUserDao().getByMail(mail);
		if(user != null){
			Hibernate.initialize(user);
		}
		return user;
	}

	public User getUserById(String id) throws BlogerException {
		User user = getUserDao().get(id);
		if(user != null){
			Hibernate.initialize(user);
		}
		return user;
	}

	public void saveOrUpdateUser(User user) throws BlogerException {
		if(StringUtil.isBlank(user.getId())){
			//add user then check if this mail in use
			User other = getUserDao().getByMail(user.getEmail());
			if(other != null){
				throw new AlreadyExistException();
			}
		}
		getUserDao().saveOrUpdate(user);
	}

}
